/*
 * @lc app=leetcode.cn id=25 lang=javascript
 *
 * [25] K 个一组翻转链表
 */

// @lc code=start
/**
 * Definition for singly-linked list.
 * function ListNode(val, next) {
 *     this.val = (val===undefined ? 0 : val)
 *     this.next = (next===undefined ? null : next)
 * }
 */
/**
 * @param {ListNode} head
 * @param {number} k
 * @return {ListNode}
 */
var reverseKGroup = function (head, k) {
  if (head === null || head.next === null || k < 2) {
    return head;
  }

  // 反转节点
  const reverseNode = (head, n) => {
    // 判断剩余节点是否小于k
    let cur = head;
    let cnt = n;
    while (--cnt && cur) {
      cur = cur.next;
    }
    if (cur === null) {
      return head;
    }

    // 递归到这里结束
    if (n === 1) {
      return head;
    }
    let tail = head.next;
    let p = reverseNode(head.next, n - 1);
    head.next = tail.next;
    tail.next = head;
    return p;
  };

  const dummp = new ListNode(0, head);
  let pre = dummp;

  while (true) {
    pre.next = reverseNode(pre.next, k);
    // 每次往后走k个节点，pre要保留是反转节点的前一个节点
    for (let i = 0; i < k && pre; i++) {
      pre = pre.next;
    }
    if (!pre) break;
  }

  return dummp.next;
};
// @lc code=end
